package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.BrandVo;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.HttpsURLConnection;
import java.util.List;

/**
 * @ClassName: BrandController
 * @Description: 品牌
 * @Author: sunt
 * @Date: 2019/11/11 15:45
 * @Version 1.0
 **/
@RequestMapping("brand")
@RestController
public class BrandController {

    @Autowired
    private BrandService brandService;

    /**
     * 品牌分页查询
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @param key
     * @return
     */
    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> queryBrandByPage(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                                              @RequestParam(value = "rows", defaultValue = "5") Integer rows,
                                                              @RequestParam(value = "sortBy", required = false) String sortBy,
                                                              @RequestParam(value = "desc", defaultValue = "false") Boolean desc,
                                                              @RequestParam(value = "key", required = false) String key) {
        try {
            PageResult<Brand> result = brandService.queryBrandByPageAndSort(page, rows, sortBy, desc, key);
            if(null == result || result.getItems().size() == 0) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 保存品牌
     * @param brand
     * @param cids
     * @return
     */
    @PostMapping("saveBrand")
    public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam("cids")List<Long> cids) {
        try {
            brandService.saveBrand(brand,cids);
            return new ResponseEntity<>(HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 更新品牌
     * @param brandVo
     * @return
     */
    @PutMapping("saveBrand")
    public ResponseEntity<Void> updateBrand(BrandVo brandVo) {
        try {
            brandService.updateBrand(brandVo);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
